import 'dart:convert';
import 'package:explore/tool/toolweb.dart';
import 'package:flutter/material.dart' hide Page;
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';
import '../provider/person_info.dart';
import 'package:http/http.dart' as http;

class JoinAliance extends StatefulWidget {
  const JoinAliance({super.key});

  @override
  State<StatefulWidget> createState() => _JoinAliance();
}

class _JoinAliance extends State<JoinAliance> {
  List memberList = [];
  @override
  void initState() {
    super.initState();
    Future.delayed(Duration.zero, () {
      final personInfo = Provider.of<PersonInfo>(context, listen: false);
      var url = Uri.parse('http://127.0.0.1:5000/join_show');
      var headers = {'Content-Type': 'application/json;charset=utf-8'};
      var body =
          jsonEncode({'alliance': personInfo.alliance, 'act': personInfo.act});
      final request = http.Request('get', url);
      request.headers.addAll(headers);
      request.body = body;
      request.send().then((value) {
        http.Response.fromStream(value).then((response) {
          setState(() {
            memberList = jsonDecode(response.body)["msg"];
          });
        });
      }).catchError((value) {
        Fluttertoast.showToast(msg: '初始化异常');
      });
    });
  }

  void agree(PersonInfo person, String name) async {
    final url = Uri.parse('http://127.0.0.1:5000/join_alliance_agree');
    final headers = {'Content-Type': 'application/json;charset=utf-8'};
    final body = jsonEncode({'name': name});
    var response = await http.post(url, headers: headers, body: body);
    final responseBody = response.body;
    var jsonData = jsonDecode(responseBody);
    if (response.statusCode == 200 && jsonData["code"] == "200") {
      Fluttertoast.showToast(msg: '已同意入盟');
      memberList.remove(name);
      setState(() {});
    } else {
      Fluttertoast.showToast(msg: '入盟失败');
    }
  }

  void reject(PersonInfo person, String name) async {
    final url = Uri.parse('http://127.0.0.1:5000/join_alliance_reject');
    final headers = {'Content-Type': 'application/json;charset=utf-8'};
    final body = jsonEncode({'name': name});
    var response = await http.post(url, headers: headers, body: body);
    final responseBody = response.body;
    var jsonData = jsonDecode(responseBody);
    if (response.statusCode == 200 && jsonData["code"] == "200") {
      Fluttertoast.showToast(msg: '已拒绝入盟');
      memberList.remove(name);
      setState(() {});
    } else {
      Fluttertoast.showToast(msg: '拒绝失败');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Toolweb(
      name: "成员加入",
      list: memberList,
      agree: agree,
      reject: reject,
    );
  }
}
